import axios from 'axios';
import { type Composer } from 'vue-i18n';
import dayjs from 'dayjs';
import languages from '@/shared/config/languages';

export default class TranslationService {
  private readonly i18n: Composer;
  private languages = languages();

  constructor(i18n: Composer) {
    this.i18n = i18n;
  }
<%_ if (microfrontend) { _%>

  loadTranslations({ currentLanguage, urlPrefix, hash }: { currentLanguage: string; urlPrefix: string; hash: string }) {
    if (!this.i18n) return;
    axios.get(`${urlPrefix}i18n/${currentLanguage}.json?_=${hash}`).then((res: any) => {
      if (res.data) {
        this.i18n.mergeLocaleMessage(currentLanguage, res.data);
      }
    });
  }
<%_ } _%>

  async refreshTranslation(newLanguage: string) {
    if (this.i18n && !this.i18n.messages[newLanguage]) {
<%_ if (microfrontend) { _%>
      const res = await axios.get(`i18n/${newLanguage}.json?_=${I18N_HASH}`);
      this.i18n.setLocaleMessage(newLanguage, res.data);
<%_ } else { _%>
      const translations = (await import(`../../i18n/${newLanguage}/${newLanguage}.js`)).default;
      this.i18n.setLocaleMessage(newLanguage, translations);
<%_ } _%>
    }
  }

  setLocale(lang: string) {
    dayjs.locale(lang);
    this.i18n.locale.value = lang;
    axios.defaults.headers.common['Accept-Language'] = lang;
    document.querySelector('html').setAttribute('lang', lang);
<%_ if (enableI18nRTL) { _%>
    this.updatePageDirection(lang);
<%_ } _%>
  }
<%_ if (enableI18nRTL) { _%>

    private isRTL(lang: string): boolean {
      return this.languages[lang]?.rtl;
    }

    private updatePageDirection(currentLanguage: string): void {
      document.querySelector('html').setAttribute('dir', this.isRTL(currentLanguage) ? 'rtl' : 'ltr');
    }
<%_ } _%>

  isLanguageSupported(lang: string) {
    return Boolean(this.languages[lang]);
  }

  getLocalStoreLanguage(): string | null {
    return localStorage.getItem('currentLanguage');
  }
}
